import {Button, Flex, Form, Input, Modal, Radio, Select} from "antd";
import {Conversations, ConversationsProps} from "@ant-design/x";
import {DeleteOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";
import {useEffect, useState} from "react";

import type {Conversation} from "@ant-design/x/es/conversations/interface";
import {
  ConversationMenuPayload,
  createConversation,
  deleteConversation,
  editConversation,
  getConversation,
  train,
} from "../../service/conversationApi.ts";

interface ConversationProps {
    conversations: ConversationMenuPayload[];
    setConversations: (conversations: ConversationMenuPayload[]) => void;
    conversationType: string;
    setConversationId: (s: string) => void;
    conversationId: string;
    setConversationType: string;
    onRemove: (s: string) => void;
    onTitleUpdate: (convId: string, title: string) => void;
}

export const AiConversations = (props: ConversationProps) => {
    const {
        conversations,
        setConversations,
        conversationId,
        setConversationId,
        onRemove,
        onTitleUpdate,
    } = props;

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSelectionModalOpen, setIsSelectionModalOpen] = useState(false);
    const [isSemanticModalOpen, setIsSemanticModalOpen] = useState(false);
    const [isSQLTrainingModalOpen, setIsSQLTrainingModalOpen] = useState(false);
    const [conversationType, setConversationType] = useState("T2T");
    const [onUpdateConvId, setOnUpdateConvId] = useState("");
    const [updateTitle, setUpdateTitle] = useState("");
    const [tableName, setTableName] = useState("");
    const [datasource, setDatasource] = useState("");

    const [form] = Form.useForm();


    const [form2] = Form.useForm();


    useEffect(() => {
        // Fetch the initial values from the API
        getConversation(conversationId).then((res) => {
            if (res.content) {
                setDatasource(res.content.datasource)
                setTableName(res.content.tableName);
                form.setFieldsValue({
                  question: res.content.nl2sqlQuestion,
                  content: res.content.nl2sqlContent,
                  trainType: res.content.nl2sqlTrainType,
                  datasource: res.content.datasource,
                  tableName: res.content.tableName,
                });
                form2.setFieldsValue({
                    datasource: res.content.datasource,
                    tableName: res.content.tableName,
                });
            }
        });
    }, [conversationId]);


    const menuConfig: ConversationsProps["menu"] = (conversation) => {
        const items = [
            {
                label: "修改名称",
                key: "edit",
                icon: <EditOutlined/>,
                onClick: () => {
                    setIsModalOpen(true);
                    setOnUpdateConvId(conversation.key);
                },
            },
            {
                label: "删除会话",
                key: "del",
                icon: <DeleteOutlined/>,
                danger: true,
                onClick: () => {
                    deleteConversation(conversation.key).then((res) => {
                        if (res.success) {
                            onRemove(conversation.key);
                        }
                    });
                },
            },
        ];

        if (conversation.conversationType === "NL2SQL") {
            items.push({
                    label: "语义建模",
                    key: "semantic",
                    icon: <EditOutlined/>,
                    onClick: () => {
                        setIsSemanticModalOpen(true);
                    },
                },
                {
                    label: "SQL 训练",
                    key: "sqlTraining",
                    icon: <EditOutlined/>,
                    onClick: () => {
                        setIsSQLTrainingModalOpen(true);
                    },
                },
            );
        }

        return {items};
    };

    const onCreate = () => {
        setIsSelectionModalOpen(true);
    };

    const handleCreateConversation = () => {
        createConversation(conversationType).then((res) => {
            const conv = res.content;
            if (conv) {
                setConversations([
                    ...conversations,
                    {conversationId: conv.conversationId, title: conv.title, conversationType: conv.conversationType},
                ]);
                onConversationChange(conv.conversationId);
            }
            setIsSelectionModalOpen(false);
        });
    };

    const onConversationChange = (value: string) => {
        setConversationId(value);
    };

    const handleTitleUpdate = () => {
        editConversation(onUpdateConvId, updateTitle).then((res) => {
            if (res.success) {
                onTitleUpdate(onUpdateConvId, updateTitle);
                setIsModalOpen(false);
            }
        });
    };

    const handleSemanticSubmit = (values) => {
        // Call the API to save the semantic modeling data
        values.conversationId = conversationId;
        train(values);
        setIsSemanticModalOpen(false);
    };

    const handleSQLTrainingSubmit = (values) => {
        // Call the API to save the SQL training data
        values.conversationId = conversationId;
        train(values);
        setIsSQLTrainingModalOpen(false);
    };

    return (
        <Flex style={{height: "100%", background: "white"}} vertical>
            <Conversations
                defaultActiveKey={conversationId}
                activeKey={conversationId}
                menu={menuConfig}
                items={conversations.map((value) => {
                    return {
                        key: value.conversationId,
                        label: value.title,
                        conversationType: value.conversationType,
                    } as Conversation;
                })}
                onActiveChange={onConversationChange}
            />
            <Flex align={"center"} justify={"center"}>
                <Button
                    style={{width: 160}}
                    icon={<PlusOutlined/>}
                    onClick={onCreate}
                >
                    新建会话
                </Button>
            </Flex>
            <Modal
                title="修改会话名称"
                open={isModalOpen}
                onOk={handleTitleUpdate}
                onCancel={() => setIsModalOpen(false)}
            >
                <Input
                    onChange={(e) => {
                        setUpdateTitle(e.target.value);
                    }}
                />
            </Modal>
            <Modal
                title="选择会话类型"
                open={isSelectionModalOpen}
                onOk={handleCreateConversation}
                onCancel={() => setIsSelectionModalOpen(false)}
            >
                <Radio.Group
                    onChange={(e) => setConversationType(e.target.value)}
                    value={conversationType}
                >
                    <Radio value="T2T">普通对话</Radio>
                    <Radio value="NL2SQL">自然语言转SQL(nl2sql)</Radio>
                </Radio.Group>
            </Modal>
            <Modal
                title="语义建模"
                open={isSemanticModalOpen}
                onOk={() => form.submit()}
                onCancel={() => setIsSemanticModalOpen(false)}
            >
                <Form form={form} onFinish={handleSemanticSubmit}
                      initialValues={{question: "", content: "", trainType: "", tableName: ""}}>
                    <Form.Item name="question" label="模型描述" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="content" label="模型创建语句" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="trainType" label="策略" rules={[{required: true}]}>
                        <Select>
                            {/* <Select.Option value="SQL">SQL</Select.Option>*/}
                            <Select.Option value="DDL">DDL</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="datasource" label="数据库名称" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="tableName" label="数据库表名称" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="SQL 训练"
                open={isSQLTrainingModalOpen}
                onOk={() => form2.submit()}
                onCancel={() => setIsSQLTrainingModalOpen(false)}
            >
                <Form form={form2} onFinish={handleSQLTrainingSubmit}
                      initialValues={{question: "", content: "", trainType: "SQL",datasource:datasource,tableName: tableName}}>
                    <Form.Item name="question" label="SQL语义描述" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="content" label="SQL语句" rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="trainType" label="Policy" rules={[{required: true}]} style={{display: 'none'}}>
                        <Select>
                            <Select.Option value="SQL">SQL</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="datasource" label="datasource" rules={[{required: true}]} style={{display: 'none'}}>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="tableName" label="tableName" rules={[{required: true}]} style={{display: 'none'}}>
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>
        </Flex>
    );
};